package com.comtop.topcloud.device.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.comtop.topcloud.device.mapper.EnergyEfficiencyManagementMapper;
import com.comtop.topcloud.device.model.EnergyConfig;
import com.comtop.topcloud.device.model.mysql.EnergyEfficiencyManagement;
import com.comtop.topcloud.device.service.EnergyEfficiencyManagementService;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class EnergyEfficiencyManagementServiceImpl extends ServiceImpl<EnergyEfficiencyManagementMapper, EnergyEfficiencyManagement> implements EnergyEfficiencyManagementService {

    /**
     * redis key
     */
    public static final String MANAGEMENT_CONFIG_KEY = "MANAGEMENT_CONFIG_KEY";

    @Autowired
    private RedissonClient redisson;

    @Override
    public List<EnergyConfig> getEnergyConfigByMonitorType(Integer monitorType) {
        if (monitorType == null) {
            return null;
        }
        RMapCache<String, List<EnergyConfig>> configRMapCache = redisson.getMapCache(MANAGEMENT_CONFIG_KEY);
        String key = MANAGEMENT_CONFIG_KEY + monitorType;
        List<EnergyConfig> energyConfigs = configRMapCache.get(key);

        // 如果缓存中有数据，直接返回
        if (!CollectionUtils.isEmpty(energyConfigs)) {
            return energyConfigs;
        }

        energyConfigs = baseMapper.getEnergyConfigByMonitorType(String.valueOf(monitorType));
        if (CollectionUtils.isEmpty(energyConfigs)) {
            EnergyConfig defaultEnergyConfig = new EnergyConfig();
            energyConfigs = new ArrayList<>();
            energyConfigs.add(defaultEnergyConfig);  // 将默认对象添加到列表
            configRMapCache.put(key, energyConfigs, 30, TimeUnit.MINUTES);  // 设置缓存过期时间
        } else {
            // 数据库有数据，存储到缓存中
            configRMapCache.put(key, energyConfigs, 30, TimeUnit.MINUTES);
        }

        return energyConfigs;
    }
}
